<template>
  <div>
    <van-search
      v-model="keyWord"
      show-action
      label="地址"
      placeholder="请输入搜索关键词"
      background="#ff734c"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div>
      <h5>搜索记录</h5>
      <div class="histories">
        <div v-for="his in histories" @click="clickHis(his)" :key="his" class="his">
          {{his}}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// histories
export default {
  data () {
    return {
      keyWord: '',
      histories: localStorage.getItem('histories')
        ? JSON.parse(localStorage.getItem('histories'))
        : []
    }
  },
  methods: {
    clickHis (his) {
      // 点击搜索历史记录
      this.keyWord = his
      this.onSearch()
    },
    onSearch () {
      // 搜索
      // 进入搜索结果页 将关键字 传入
      /*
       1 先取缓存 转换成数组 用变量接收
        数组 unshift 插入新的

        存回去 JSON.stringify()  去重
      */
      let histories = localStorage.getItem('histories')
        ? JSON.parse(localStorage.getItem('histories'))
        : []
      histories.unshift(this.keyWord)
      // 数组去重
      histories = [...new Set(histories)]
      if (histories.length > 5) {
        histories.pop()
      }
      localStorage.setItem('histories', JSON.stringify(histories))
      this.$router.push({
        path: '/searchResult',
        query: {
          word: this.keyWord
        }
      })
    }
  },
  name: 'Search'
}
</script>

<style lang="scss" scoped>
.histories{
  display: flex;
  flex-wrap: wrap;
  .his{
    padding: 5px 15px;
    background-color: #eee;
    color:#666;
    margin: 5px;
  }

}
</style>
